package com.cloud.system.controller;

import com.cloud.common.domain.Result;
import com.cloud.controller.BaseController;
import com.cloud.entity.SysDept;
import com.cloud.enums.BusinessType;
import com.cloud.common.enums.CheckType;
import com.cloud.common.enums.DeptType;
import com.cloud.logs.Logs;
import com.cloud.security.aop.RequestPermissions;
import com.cloud.user_info.service.ISysDeptService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 部门管理
 *
 * @author hhb, yzj
 */
@Tag(name = "部门信息")
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {

    @Autowired
    private ISysDeptService deptService;

    @Operation(summary = "查询部门列表")
    @RequestPermissions("system:dept:list")
    @GetMapping("/list")
    public Result list(SysDept dept) {
        return Result.success("查询成功", deptService.selectDeptList(dept));
    }

    @Operation(summary = "查询部门列表(排除节点)")
    @Parameter(name = "deptId", description = "部门ID")
    @RequestPermissions("system:dept:list")
    @GetMapping("/list/exclude")
    public Result excludeChild(Long deptId) {
        List<SysDept> deptList = deptService.selectDeptList(new SysDept());
        deptList.removeIf(dept -> dept.getDeptId().intValue() == deptId
                || ArrayUtils.contains(StringUtils.split(dept.getAncestors(), ","), deptId + ""));
        return Result.success("查询成功", deptList);
    }

    @Operation(summary = "Feign内部调用(根据ID查子级部门主键列表)")
    @RequestMapping(value = "/inAuth/selectChildDeptId", method = {RequestMethod.POST, RequestMethod.GET})
    public Result selectChildDeptId(Long deptId) {
        return Result.success("查询成功", deptService.selectChildDeptId(deptId));
    }

    @Operation(summary = "查询部门详情")
    @Parameter(name = "deptId", description = "部门ID")
    @RequestPermissions("system:dept:query")
    @GetMapping("/getInfo")
    public Result getInfo(Long deptId) {
        return Result.success("查询成功", deptService.selectDeptById(deptId));
    }

    @Operation(summary = "查询树状部门列表")
    @GetMapping("/treeSelect")
    public Result treeSelect(SysDept dept) {
        return Result.success("查询成功", deptService.buildDeptTreeSelect(dept));
    }

    @Operation(summary = "查询角色部门列表")
    @Parameter(name = "roleId", description = "角色ID")
    @GetMapping("/roleDeptTreeSelect")
    public Result roleDeptTreeSelect(Long roleId) {
        Map<String, Object> map = new HashMap<>();
        map.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        map.put("deptList", deptService.buildDeptTreeSelect(new SysDept()));
        return Result.success("查询成功", map);
    }

    @Operation(summary = "新增部门信息")
    @Logs(title = "新增部门信息", businessType = BusinessType.INSERT)
    @RequestPermissions("system:dept:add")
    @PostMapping("/insert")
    public Result insert(@RequestBody SysDept dept) {
        if (StringUtils.equals(CheckType.NOT_UNIQUE.getCode(), deptService.checkDeptNameUnique(dept))) {
            return Result.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        return deptService.insertDept(dept);
    }

    @Operation(summary = "修改部门信息")
    @Logs(title = "修改部门信息", businessType = BusinessType.UPDATE)
    @RequestPermissions("system:dept:edit")
    @PostMapping("/update")
    public Result update(@RequestBody SysDept dept) {
        if (StringUtils.equals(CheckType.NOT_UNIQUE.getCode(), deptService.checkDeptNameUnique(dept))) {
            return Result.error("修改部门[" + dept.getDeptName() + "]失败,部门名称已存在");
        } else if (dept.getParentId().equals(dept.getDeptId())) {
            return Result.error("修改部门[" + dept.getDeptName() + "]失败,上级部门不能是自己");
        } else if (Integer.valueOf(DeptType.DEPT_DISABLE.getCode()).equals(dept.getStatus())
                && deptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0) {
            return Result.error("该部门包含未停用的子部门");
        }
        return deptService.updateDept(dept);
    }

    @Operation(summary = "删除部门信息")
    @Parameter(name = "deptId", description = "部门ID")
    @Logs(title = "删除部门信息", businessType = BusinessType.DELETE)
    @RequestPermissions("system:dept:remove")
    @PostMapping("/remove")
    public Result remove(Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return Result.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return Result.error("部门存在用户,不允许删除");
        }
        return deptService.deleteDeptById(deptId);
    }

    @Operation(summary = "查询所有部门级节点列表")
    @GetMapping("/getLowerSelect")
    public Result getLowerSelect() {
        SysDept sysDept = new SysDept();
        sysDept.setNodeType(DeptType.IS_LOWEST.getCode());
        return Result.success("查询成功", deptService.selectDeptByLower(sysDept));
    }

    @Operation(summary = "Feign内部调用(根据部门ID查询区域信息)")
    @RequestMapping(value = "/inAuth/getInSuperAreaDept", method = {RequestMethod.POST, RequestMethod.GET})
    public Result getInSuperAreaDept(Long deptId) {
        return Result.success("查询成功", deptService.getSuperAreaDept(deptId));
    }

    @Operation(summary = "Feign内部调用(根据部门全称查询部门对象)")
    @RequestMapping(value = "/inAuth/getInDeptByName", method = {RequestMethod.POST, RequestMethod.GET})
    public Result getInDeptByName(String deptName) {
        return Result.success("查询成功", deptService.selectDeptByName(deptName));
    }

    @Operation(summary = "Feign内部调用(根据部门id查询部门对象)")
    @RequestMapping(value = "/inAuth/getInDeptByDeptId", method = {RequestMethod.POST, RequestMethod.GET})
    public Result getInDeptByDeptId(Long deptId) {
        return Result.success("查询成功", deptService.getInDeptByDeptId(deptId));
    }

    @Operation(summary = "Feign内部调用(根据部门id查询用户ids)")
    @RequestMapping(value = "/inAuth/getDeptUserIdsById", method = {RequestMethod.POST, RequestMethod.GET})
    public Result getDeptUserIdsById(String deptIds) {
        return Result.success("查询成功", deptService.getDeptUserIdsById(deptIds));
    }

}
